package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.HServiceOrderMapper;
import com.flea.hclv.model.dao.HTourGroupVisitorMapper;
import com.flea.hclv.model.dao.HTravelGroupMapper;
import com.flea.hclv.model.dao.HVisitorMapper;
import com.flea.hclv.model.entity.HServiceOrder;
import com.flea.hclv.model.entity.HTourGroupVisitor;
import com.flea.hclv.model.entity.HTravelGroup;
import com.flea.hclv.model.entity.HVisitor;
import com.flea.hclv.model.entity.vo.HTravelGroupChargePersonVo;
import com.flea.hclv.service.HTourGroupVisitorService;
import com.flea.hclv.util.ExportExcelUtil;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.entity.OrgDept;
import com.flea.system.platform.session.FleaOrgUtils;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @program: project
 * @description: 团与游客关联关系
 * @author: shiliqiang
 * @create: 2018-11-03 13:30
 * @version: 1.0
 */
@Service
public class HTourGroupVisitorServiceImpl implements HTourGroupVisitorService {
	@Autowired
	private HTourGroupVisitorMapper tourGroupVisitorMapper;
	@Autowired
	private HTravelGroupMapper traveGroupMapper;
	@Autowired
	private HVisitorMapper visitorMapper;
	@Autowired
	private HServiceOrderMapper hServiceOrderMapper;

	@Override
	public ServerResponse<String> findAllUserByGroupId(String groupId,
													   HttpServletResponse response) {
		ServletOutputStream out = null;  
        FileInputStream ips = null;  
		if (StringUtils.isBlank(groupId)) {
			return ServerResponse.createByErrorMessage("团ID为空");
		}
		HTravelGroup hTravelGroup = traveGroupMapper
				.selectByPrimaryKey(groupId);
		if (hTravelGroup == null) {
			return ServerResponse.createByErrorMessage("没有找到团信息");
		}
		List<HTourGroupVisitor> rel = tourGroupVisitorMapper
				.selectByGroupId(groupId);
		if (CollectionUtils.isEmpty(rel)) {
			return ServerResponse.createByErrorMessage("没有找到团关联信息");
		}
		Set<String> visitorIds = Sets.newHashSet();

		for (HTourGroupVisitor hvs : rel) {
			visitorIds.add(hvs.getVisitorId());
		}
		List<HVisitor> visitors = visitorMapper.selectSeatByVisitorIdsAndTimeTableId(visitorIds,hTravelGroup.getTimeTableId());
		JSONArray jsonArray = new JSONArray();
		for (HVisitor visitor : visitors) {

			JSONObject jsonObject = new JSONObject();
			String type = visitor.getType();
			jsonObject.put("姓名", visitor.getZhName());
			jsonObject.put("英文名", visitor.getEnName());
            jsonObject.put("游客类型", HCarVisitorServiceImpl.setVisitorType(type));
			String sex=visitor.getSex();
			jsonObject.put("性别",HCarVisitorServiceImpl.setSexValue(sex));
			String certificates = visitor.getCertificates();
			jsonObject.put("证件类型", HCarVisitorServiceImpl.setCertificatesTypeValue(certificates));
			jsonObject.put("证件号码", visitor.getCertificatesNumber());
			Date date = visitor.getBirthDate();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			String dateString = formatter.format(date);
			jsonObject.put("出生日期", dateString);
			jsonObject.put("手机号", visitor.getPhone());
			jsonObject.put("车号",visitor.getCarNumber());
			jsonObject.put("座位号",visitor.getSeatNumber());
			jsonObject.put("备注",visitor.getDescription());
			jsonArray.add(jsonObject);
		}
		// 标题
		String title = hTravelGroup.getGroupName() + "旅行团名单";
		// 文件名称
		title = title.replace(" ", "_");
		String fileName = title+".xls";
		String[] titles = {  "姓名", "英文名","游客类型", "性别", "证件类型", "证件号码", "出生日期",
				"手机号","车号","座位号","备注" };
		String tempPath = System.getProperty("java.io.tmpdir");
		// 路径
		//String path = "D:\\doc";
		ExportExcelUtil.createExcel(response, tempPath, fileName, title, titles,jsonArray);
        ServerResponse<String> response1 = HCarVisitorServiceImpl.downLoadFile(tempPath, fileName, response);
        if (!response1.isSuccess()){
            return response1;
        }
        return ServerResponse.createBySuccessMessage("导出成功");
	}

	@Override
	public ServerResponse<FleaPage<HVisitor>> findAllUserByGroupIdPaging(
			int curPage, int pageSize, String groupId) {
		RowBounds rowBounds = new RowBounds(curPage, pageSize);
		List<HTourGroupVisitor> rel = tourGroupVisitorMapper.findByGroupId(
				rowBounds, groupId);
		FleaPage<HTourGroupVisitor> temp = new FleaPage<>(rel);
    List<HVisitor> visitors = new ArrayList<>();
		List<String> visitorIds = new ArrayList<String>();
		for (HTourGroupVisitor hvs : rel) {
			visitorIds.add(hvs.getVisitorId());
		}
		if(visitorIds.size()>0){
      visitors = visitorMapper.findByIds(visitorIds);
      for (HVisitor visitor : visitors){
          visitor.setSex(HCarVisitorServiceImpl.setSexValue(visitor.getSex()));
      }
    }
		FleaPage<HVisitor> result = new FleaPage<HVisitor>();
		result.setCurPageData(visitors);
		result.setPageSize(pageSize);
		result.setCurPage(curPage);
		result.setAllDataCount((int) temp.getAllDataCount());
		return ServerResponse.createBySuccess("成功", result);
	}

	@Override
	public ServerResponse<HTravelGroup> updateStatusToOk(String groupId,HttpServletRequest request)
      throws Exception {
		String userId = FleaOrgUtils.getCurUserUuid(request);
		
		HTravelGroup hGroup = 	traveGroupMapper.selectByPrimaryKey(groupId);
		if(null==hGroup){
			return ServerResponse.createByErrorMessage("团不存在");
		}
		if(!hGroup.getStatus().equals(HConstant.HCLV_VISITOR_GROUP_ISNO)){
			return ServerResponse.createByErrorMessage("团已封");
		}
		hGroup.setDepartureTime(new Date());
		hGroup.setStatus(HConstant.HCLV_VISITOR_GROUP_ISYES);
		hGroup.setModifyUser(userId);

    boolean result;
    try {
      result = traveGroupMapper.updateByPrimaryKeySelective(hGroup)==1;
    } catch (Exception e) {
    throw  new Exception("操作失败");
    }
    if(!result){
			return ServerResponse.createByErrorMessage("操作失败");
		}
		return ServerResponse.createBySuccessMessage("操作成功");
	}

  @Override
  public ServerResponse addGroupChargePerson(HttpServletRequest request,
      HTravelGroupChargePersonVo pvo)  throws Exception{

	 HTravelGroup group =   traveGroupMapper.selectByPrimaryKey(pvo.getGroupId());
	 if(null==group){
	   return ServerResponse.createByErrorMessage("该团已经不存在了，请确认是否操作正确");
   }
   OrgDept curOrg =  FleaOrgUtils.getCurrentUserDept(request);


	 if(null==curOrg||!(curOrg.getDeptUuid().equals(group.getServiceOrgId()))){
     return ServerResponse.createByErrorMessage("抱歉，您没有修改的权限");
   }
  if(HConstant.HCLV_VISITOR_GROUP_ISREBACK.equals(group.getStatus())||HConstant.HCLV_VISITOR_GROUP_ISCLOSE.equals(group.getStatus())){
    return ServerResponse.createByErrorMessage("此状态，不可进行更换或指定负责人");
  }

   String personName = pvo.getChargePersonName();
	 String phone = pvo.getChargePersonPhone();
	 String userUuid = FleaOrgUtils.getCurUserUuid(request);

	 group.setChargePerson(personName);
	 group.setChargePersonPhone(phone);
	 group.setModifyUser(userUuid);
    boolean   result = false;
    try {
       result = traveGroupMapper.updateByPrimaryKeySelective(group)==1;
    } catch (Exception e) {
     throw new Exception("负责人指定失败");
    }

    return ServerResponse.createBySuccessMessage("负责人指定成功");
  }

  @Override
  public ServerResponse<HTravelGroup> updateStatusIsBack(String groupId, HttpServletRequest request)
      throws Exception {
    String userId = FleaOrgUtils.getCurUserUuid(request);

    HTravelGroup hGroup = 	traveGroupMapper.selectByPrimaryKey(groupId);
    if(null==hGroup){
      return ServerResponse.createByErrorMessage("团不存在");
    }
    if(hGroup.getStatus().equals(HConstant.HCLV_VISITOR_GROUP_ISREBACK)){
      return ServerResponse.createByErrorMessage("已回团，不可重复操作");
    }
    if(hGroup.getStatus().equals(HConstant.HCLV_VISITOR_GROUP_ISCLOSE)){
      return ServerResponse.createByErrorMessage("已完成，并关闭，不可操作");
    }
    if(hGroup.getStatus().equals(HConstant.HCLV_VISITOR_GROUP_ISNO)){
      return ServerResponse.createByErrorMessage("未封团，此团不可以设置为回团");
    }
    hGroup.setGoBackTime(new Date());
    hGroup.setStatus(HConstant.HCLV_VISITOR_GROUP_ISREBACK);
    hGroup.setModifyUser(userId);

    boolean result = false;
    try {
      result = traveGroupMapper.updateByPrimaryKeySelective(hGroup)==1;
    } catch (Exception e) {
      throw  new Exception("回团操作失败");
    }
    if(!result){
      return ServerResponse.createByErrorMessage("回团操作失败");
    }
    return ServerResponse.createBySuccessMessage("回团操作成功");
  }

  @Override
  public ServerResponse<HTravelGroup> updateStatusIsClose(String groupId,
      HttpServletRequest request) throws Exception {
    String userId = FleaOrgUtils.getCurUserUuid(request);

    HTravelGroup hGroup = 	traveGroupMapper.selectByPrimaryKey(groupId);
    if(null==hGroup){
      return ServerResponse.createByErrorMessage("团不存在");
    }
    if(hGroup.getStatus().equals(HConstant.HCLV_VISITOR_GROUP_ISCLOSE)){
      return ServerResponse.createByErrorMessage("团已关闭，不可重复操作");
    }

    if(hGroup.getStatus().equals(HConstant.HCLV_VISITOR_GROUP_ISNO)){
      return ServerResponse.createByErrorMessage("未封团，此团不可以设置为关闭状态");
    }
    if(!hGroup.getStatus().equals(HConstant.HCLV_VISITOR_GROUP_ISREBACK)){
      return ServerResponse.createByErrorMessage("未封团，此团不可以设置为关闭状态");
    }
    hGroup.setStatus(HConstant.HCLV_VISITOR_GROUP_ISCLOSE);
    hGroup.setModifyUser(userId);

    boolean result = false;
    try {
      result = traveGroupMapper.updateByPrimaryKeySelective(hGroup)==1;
    } catch (Exception e) {
      throw  new Exception("关闭团操作失败");
    }
    if(!result){
      return ServerResponse.createByErrorMessage("关闭团操作失败");
    }
    return ServerResponse.createBySuccessMessage("关闭团操作成功");
  }

  @Override
  public ServerResponse<HTravelGroup> updateStatusToUnOk(String groupId, HttpServletRequest request)
      throws Exception {
    {
      String userId = FleaOrgUtils.getCurUserUuid(request);

      HTravelGroup hGroup = 	traveGroupMapper.selectByPrimaryKey(groupId);
      if(null==hGroup){
        return ServerResponse.createByErrorMessage("团不存在");
      }
      if(!hGroup.getStatus().equals(HConstant.HCLV_VISITOR_GROUP_ISYES)){
        return ServerResponse.createByErrorMessage("此团不在已封团状态，不可进行该操作");
      }
      HServiceOrder hserviceOrder = hServiceOrderMapper.findByGroupId(groupId);
      if(null!=hserviceOrder){
        return ServerResponse.createByErrorMessage("此团已经下单，不可进行解封");
      }

      hGroup.setStatus(HConstant.HCLV_VISITOR_GROUP_ISNO);
      hGroup.setModifyUser(userId);

      boolean result = false;
      try {
        result = traveGroupMapper.updateByPrimaryKeySelective(hGroup)==1;
      } catch (Exception e) {
        throw  new Exception("操作失败");
      }
      if(!result){
        return ServerResponse.createByErrorMessage("操作失败");
      }
      return ServerResponse.createBySuccessMessage("操作成功");
    }
  }
}
